# -*- coding: utf-8 -*-
from sdk import *

class WeixinSDK:

	def __init__(self,appId,secret):
		self.AppId = appId
		self.Secret = secret
		self.Token = None

	def __getAccessToken(self):
		if self.Token is None:
			url = "/token?grant_type=client_credential&appid=%s&secret=%s"
			apiUrl = url %  (self.AppId,self.Secret)
			resData = self.__getResponse(apiUrl)
			self.Token = resData["access_token"]

		return self.Token

	def __getResponse(self,url):
		reqUrl = "https://api.weixin.qq.com/cgi-bin" + url
		req = urllib2.Request(reqUrl)
		res = urllib2.urlopen(req)
		resData = json.loads(res.read())
		return resData

	def __postResponse(self,url,data):
		#data = {"key":"value","key":"value"}
		reqUrl = "https://api.weixin.qq.com/cgi-bin" + url
		#headers = {"Content-type":"application/json"}
		#encodeData = json.JSONEncoder().encode(data)
		#headers = {"Content-Type":"application/x-www-form-urlencoded"} 
		#encodeData = urllib.urlencode(data)

		#req = urllib2.Request(url = reqUrl,data = data,headers = headers)
		req = urllib2.Request(url = reqUrl,data = data)
		res = urllib2.urlopen(req)
		resData = json.loads(res.read())
		return resData
	
	def __validateResponse(self,resData):
		if not resData.has_key("errcode"):
			return True

		if resData.get("errcode") == 0 :
			return True

		if resData.get("errcode") == 45015: # 回复时间超过限制
			return True
			
		if resData.get("errcode") == 42001: # access_token超时
			self.Token = None
			return False

		raise Exception(resData)
		
	#创建自定义菜单
	def createMenu(self,menus):
		url = "/menu/create?access_token=%s"
		accessToken = self.__getAccessToken()
		apiUrl = url % (accessToken)
		contentBody = menus#json.dumps(menus)
		resData = self.__postResponse(apiUrl,contentBody)
		if not self.__validateResponse(resData):
			return self.createMenu(menus)
		return resData

	#获取用户基本信息
	def getUserInfo(self,openId):
		'''
		return data struct
		{
		    "subscribe": 1,  用户是否订阅该公众号标识，值为0时，代表此用户没有关注该公众号，拉取不到其余信息。
		    "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", 用户的标识，对当前公众号唯一
		    "nickname": "Band", 	用户的昵称
		    "sex": 1, 				用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
		    "language": "zh_CN", 
		    "city": "广州", 
		    "province": "广东",
		    "country": "中国", 
		    "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0", 
		    				用户头像，最后一个数值代表正方形头像大小（有0、46、64、96、132数值可选，0代表640*640正方形头像），用户没有头像时该项为空
		   "subscribe_time": 1382694957	用户关注时间，为时间戳。如果用户曾多次关注，则取最后关注时间
		}'''
		url = "/user/info?access_token=%s&openid=%s"
		accessToken = self.__getAccessToken()
		apiUrl = url % (accessToken,openId)
		resData = self.__getResponse(apiUrl)
		if not self.__validateResponse(resData):
			return self.getUserInfo(openId)
		return resData

	#获取公众帐号关注者
	def getFollowers(self,nextOpenId):
		'''
		return data struct
		{
			"total":2,关注该公众账号的总用户数
			"count":2,拉取的OPENID个数，最大值为10000
			"data":{ 
				"openid":["","OPENID1","OPENID2"] 列表数据，OPENID的列表
			},
			"next_openid":"NEXT_OPENID" 拉取列表的后一个用户的OPENID
		}
		'''

		url = "/user/get?access_token=%s&next_openid=%s"
		accessToken = self.__getAccessToken()
		apiUrl = url % (accessToken,nextOpenId)
		resData = self.__getResponse(apiUrl)
		if not self.__validateResponse(resData):
			return self.getFollowers(nextOpenId)
		return resData
		
	
	#发送客服消息
	def sendTextMsg(self,openId,content):
		url = '/message/custom/send?access_token=%s'
		accessToken = self.__getAccessToken()
		apiUrl = url % (accessToken)
		contentBody = '{"touser": "%s","msgtype": "text","text":{"content": "%s"}}' % (str(openId), str(content))
		resData = self.__postResponse(apiUrl,contentBody)
		if not self.__validateResponse(resData):
			return self.sendTextMsg(openId,content)

		return resData














	